using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CookComputing.XmlRpc;
using System.Threading;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;



// for registry read/write
using Microsoft.Win32;

/*
 +		["log_entries"]	{Dimensions:[14]}	
+		["time"]	{13.10.2008 23:39:14}	
+		["percent_complete"]	0	
+		["currently_downloading"]	{Dimensions:[0]}	
+		["version"]	"0.13"	
+		["currently_processing"]	{Dimensions:[0]}	
+		["config_file"]	"/etc/hellanzb.conf"	
+		["test"]	12	
+		["total_dl_files"]	0	
+		["queued"]	{Dimensions:[0]}	
+		["eta"]	0	textBoxTimeLeft
+		["rate"]	0	
+		["queued_mb"]	0	
+		["hostname"]	"server"	
+		["uptime"]	"04:43"	
+		["total_dl_segments"]	0	
+		["maxrate"]	0	
+		["total_dl_nzbs"]	0	
+		["total_dl_mb"]	0	
+		["is_paused"]	true	
*/
namespace HellaRPCClient
{



    public partial class Form1 : Form
    {

        // clipboard view code
        [DllImport("user32.dll")]
        public static extern int SetClipboardViewer(int windowHandle);

        private const int WM_DRAWCLIPBOARD = 776;


        System.Windows.Forms.Timer Clock;

        private Boolean mConnected;

         private String szLastLogEntry = "";

        private bool bIsUpdating = false;

        public Form1()
        {
            
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;

            SetClipboardViewer(this.Handle.ToInt32());
            
            mConnected = false;
            Clock = new System.Windows.Forms.Timer();
            Clock.Interval = 1000;
            Clock.Tick += new EventHandler(TickUpdateForm);
            Clock.Start();

           

            listBoxQueue.Items.Clear();

            // check if autostart is activated
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (rkApp != null && rkApp.GetValue("Hellau") != null)
            {
                if (((String)rkApp.GetValue("Hellau")).Equals(Application.ExecutablePath.ToString()))
                {
                    checkBox_Autostart.Checked = true;
                }
                else
                {
                    checkBox_Autostart.Checked = false;
                }
            }

            RegistryKey minimizedKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
            if (minimizedKey != null && minimizedKey.GetValue("Minimized") != null)
            {
                if ((String)minimizedKey.GetValue("Minimized") == "TRUE")
                {
                    checkBox_StartMinimized.Checked = true;
                    Hide();
                    this.WindowState = FormWindowState.Minimized;
                }
                else
                {
                    checkBox_StartMinimized.Checked = false;
                }
            }

            RegistryKey trayKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
            if (trayKey != null && trayKey.GetValue("Tray") != null)
            {
                if ((String)trayKey.GetValue("Tray") == "TRUE")
                {
                    checkBox_minimize_tray.Checked = true;
                    
                }
                else
                {
                    checkBox_minimize_tray.Checked = false;
      
                }
            }
            if (trayKey != null && trayKey.GetValue("MonitorClipboard") != null)
            {
                if ((String)trayKey.GetValue("MonitorClipboard") == "TRUE")
                {
                    checkBox_MonitorClipboard.Checked = true;

                }
                else
                {
                    checkBox_MonitorClipboard.Checked = false;

                }
            }
          

            // try to load values from registry
            RegistryKey RegKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties");
            if (RegKey == null)
            {
                toolStripStatusLabel1.Text = "Failed to load settings from registry";
                checkBoxRemember.Checked = false;
                   }
            else
            {
                try
                {
                    String URL = (String)RegKey.GetValue("domain");
                    String password = (String)RegKey.GetValue("password");
                    if (URL.Length > 0 && password.Length > 0)
                    {
                        textBoxURL.Text = URL;
                        textBoxPassword.Text = password;
                        UpdateForm();
                        checkBoxRemember.Checked = true;
                    }


                }
                catch (Exception ex)
                {
                    toolStripStatusLabel1.Text = "Error: " + ex.Message;
                    notifyIcon1.ShowBalloonTip(500, "Hellau! Error", ex.Message, 0);
                    toolStripStatusLabel1.ForeColor = Color.Red;
        

                }
                finally
                {
                    RegKey.Close();
                    toolStripStatusLabel1.Text = "Loaded from Registry";
                    toolStripStatusLabel1.ForeColor = Color.Green;
                }
            };

            textBoxInfoText_about.Text = "Version: 1.0.0.1" + Environment.NewLine + textBoxInfoText_about.Text;
        }

        private void TickUpdateForm(object sender, EventArgs eArgs)
        {

            if (mConnected == false)
            {
                tabControl1.SelectTab(tabPageConnection);
                return;
            }

            // keep trying to connect
            if (bIsUpdating == false)
            {
                Thread thread1 = new Thread(new ThreadStart(UpdateForm));
                thread1.Start();
            }
        }

        private String iSelectedQueueItem;

        private int ClampValue(int Value, int min, int max)
        {
            return Value < min ? min : (Value > max ? max : Value);
        }

        private void UpdateForm()
        {

            if (bIsUpdating == true)
            {
                return;
            }


            bIsUpdating = true;
         
            // create the RPC proxy
            IHella hellaProxy;
            hellaProxy = XmlRpcProxyGen.Create<IHella>();

            

            try
            {
                hellaProxy.Url = textBoxURL.Text;
                hellaProxy.Credentials = new System.Net.NetworkCredential("hellanzb", textBoxPassword.Text);
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                textBoxConnnectionStatus.BackColor = Color.Red;
                textBoxStatus.Text = test.Message;
                textBoxStatus.BackColor = Color.Red;
                bIsUpdating = false;
                return;
            }

    
            // pause and continue button text
            XmlRpcStruct StatusStruct;

            try
            {
                StatusStruct = hellaProxy.Status();
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                textBoxConnnectionStatus.BackColor = Color.Red;
                notifyIcon1.ShowBalloonTip(500, "Hellau! Error", test.Message, 0);
                textBoxStatus.Text = test.Message;
                textBoxStatus.BackColor = Color.Red;
                mConnected = false;
                bIsUpdating = false;
                return;
            }

            // successfully connected!
            // write a message out
            textBoxConnnectionStatus.Text = "Connected!" + " hellanzb version: " + (String)StatusStruct["version"];
            textBoxConnnectionStatus.BackColor = Color.LawnGreen;


            //disable the password  and URL box
            textBoxPassword.ReadOnly = true;
            textBoxURL.ReadOnly = true;

            mConnected = true;

            Clock.Interval = 1000;

            // read values
            Int32 CurrentProgress = (Int32)StatusStruct["percent_complete"];
            int DLRate = (int)StatusStruct["rate"];
            Boolean paused = (Boolean)StatusStruct["is_paused"];

            

            if (paused == true)
            {
                textBoxStatus.Text = "Paused";
                Pause_Button.Text = "Continue";
                
            }
            else
            {
                if ((Int32)StatusStruct["eta"] > 0)
                {
                    textBoxStatus.Text = "Downloading";
                    textBoxStatus.BackColor = Color.LightGreen;
                }
                else
                {
                    textBoxStatus.Text = "Idle";
                    textBoxStatus.BackColor = Color.LightGreen;
                }

                Pause_Button.Text = "Pause";
            }


            if ((Int32)StatusStruct["eta"] > 0)
            {
                groupBoxCurrentDownload.Text = "Current download: " + ((int)StatusStruct["rate"]).ToString() + " kb/s";
            }
            else
            {
                groupBoxCurrentDownload.Text = "Current download: 0 kb/s";
            }

            if (paused == true)
            {
                groupBoxCurrentDownload.Text = "Current download: PAUSED";
            }




            // LOG ENTRIES
            // create the object array
            object[] LogArray = (object[])StatusStruct["log_entries"];


            if (LogArray.Length > 0)
            {
                // check the last entry and if it has changed refresh the whole thing
                XmlRpcStruct lastEntryStruct = (XmlRpcStruct)LogArray[LogArray.Length - 1];
                String szLastEntryInString = (String)("") + (String)lastEntryStruct["ERROR"] + (String)lastEntryStruct["INFO"];
                if (szLastEntryInString != szLastLogEntry)
                {
                    // display the last message in the notification area
                    if (szLastLogEntry != "")
                    {
                        if (lastEntryStruct["ERROR"] != null)
                        {
                            notifyIcon1.ShowBalloonTip(500, "Hellau! Error:", szLastEntryInString, 0);
                        }
                        else
                        {
                            notifyIcon1.ShowBalloonTip(500, "Hellau!", szLastEntryInString, 0);
                        }
                    }

                    textBoxLogFiles.Text = "";

                    foreach (object i in LogArray)
                    {
                        XmlRpcStruct temp = (XmlRpcStruct)i;
                        textBoxLogFiles.AppendText((String)temp["ERROR"] + (String)temp["INFO"] + Environment.NewLine);
                    }
                    szLastLogEntry = szLastEntryInString;
                }
            }
       
            listBoxQueue.Items.Clear();

            // current downloads
            // create the object array
            progressBarCurrentDownload.Value = ClampValue(CurrentProgress, 0, 100);

            int seconds = ((Int32)StatusStruct["eta"]);

            // TimeSpan interval = TimeSpan.FromSeconds(seconds);
            textBoxTimeLeft.Text = TimeSpan.FromSeconds(seconds).ToString() + " left";

            object[] CurrentDownloadArray = (object[])StatusStruct["currently_downloading"];
            foreach (object i in CurrentDownloadArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;
                textBoxCDownloading.Text = (String)temp["nzbName"];
                textBoxCDownloading.AppendText(" <" + ((Int32)temp["total_mb"]).ToString() + " MB>");

            }

            // Queue ENTRIES
            // create the object array
            object[] QueueArray = (object[])StatusStruct["queued"];


            foreach (object i in QueueArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;

                int position = listBoxQueue.Items.Add((String)temp["nzbName"]);
                if (((String)temp["nzbName"]).Equals(iSelectedQueueItem))
                {
                    listBoxQueue.SetSelected(position, true);
                }
            }

            //server info 

            textBoxServerInfo.Text = "";
            textBoxServerInfo.AppendText("hostname: " + (String)StatusStruct["hostname"] + Environment.NewLine);
            textBoxServerInfo.AppendText("time: " + ((DateTime)StatusStruct["time"]).ToString() + Environment.NewLine);
            textBoxServerInfo.AppendText("version: " + (string)StatusStruct["version"] + Environment.NewLine);
            textBoxServerInfo.AppendText("uptime: " + ((String)StatusStruct["uptime"]).ToString() + Environment.NewLine);
            textBoxServerInfo.AppendText("total_dl_mb: " + ((int)StatusStruct["total_dl_mb"]).ToString() + Environment.NewLine);
            textBoxServerInfo.AppendText("total_dl_nzbs: " + ((int)StatusStruct["total_dl_nzbs"]).ToString() + Environment.NewLine);

            // updates the details shown in the queue if an item is selected

            textBoxQueueDetails.Clear();


            int iSelected = listBoxQueue.SelectedIndex;
            String szSelected = (String)listBoxQueue.SelectedItem;


            // find the ID of the selected object

            foreach (object i in QueueArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;

                if (szSelected != null && szSelected.Equals((String)temp["nzbName"]))
                {
                    textBoxQueueDetails.AppendText("ID: " + ((Int32)temp["id"]).ToString() + " | ");
                    textBoxQueueDetails.AppendText((String)temp["nzbName"]);
                    object value = temp["total_mb"];
                    // require to have values during parse time
                    if (value != null)
                        textBoxQueueDetails.AppendText(" <" + ((Int32)temp["total_mb"]).ToString() + " MB>");
                }

            }

            // update the notification icon text
            if (paused == true)
            {
                notifyIcon1.Text = "Paused";
            }
            else
            {
               
                foreach (object i in CurrentDownloadArray)
                {
                    XmlRpcStruct temp = (XmlRpcStruct)i;
                    notifyIcon1.Text = "Current: ";
                    notifyIcon1.Text += TimeSpan.FromSeconds(seconds).ToString() + " left\n";
                    
                }

                int totalqueuemb = 0;
                int totalqueueitems = 0;
                foreach (object i in QueueArray)
                {
                    XmlRpcStruct temp = (XmlRpcStruct)i;
                        object value = temp["total_mb"];
                        // require to have values during parse time
                        if (value != null)
                            totalqueuemb += (int)value;

                        totalqueueitems++;
                }

                if ((int)StatusStruct["rate"] != 0)
                {
                    string text = notifyIcon1.Text + "Queue: " + totalqueueitems.ToString() + " item(s) - " + totalqueuemb.ToString() + "MB - time:" + TimeSpan.FromSeconds(totalqueuemb * 1024 / (int)StatusStruct["rate"]).ToString();
                    if (text.Length > 63)
                        text = text.Remove(63);

                    notifyIcon1.Text = text;
                }

                if (CurrentDownloadArray.Length == 0)
                {
                    notifyIcon1.Text = "idle";
                }
            }

            bIsUpdating = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!mConnected == true)
                return;


            IHella hellaProxy;
            hellaProxy = XmlRpcProxyGen.Create<IHella>();
            try
            {
                hellaProxy.Url = textBoxURL.Text;
                hellaProxy.Credentials = new System.Net.NetworkCredential("hellanzb", textBoxPassword.Text);
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                return;
            }


            XmlRpcStruct bPauseS;

            try
            {
                bPauseS = hellaProxy.Status();
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                return;
            }


            Boolean paused = (Boolean)bPauseS["is_paused"];

            if (paused == true)
            {
                try
                {
                    bPauseS = hellaProxy.Continue();
                }
                catch (Exception test)
                {
                    textBoxConnnectionStatus.Text = test.Message;
                    return;
                }
            }
            else
            {
                try
                {
                    bPauseS = hellaProxy.Pause();
                }
                catch (Exception test)
                {
                    textBoxConnnectionStatus.Text = test.Message;
                    return;
                }

            }
            UpdateForm();
        }

        private void Update_Button_Click(object sender, EventArgs e)
        {
            UpdateForm();
            checkBoxRemember.Checked = false;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
        }

        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                notifyIcon1.ContextMenuStrip = contextMenuStrip1;
                notifyIcon1.ContextMenuStrip.Show();
            }
          
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState && checkBox_minimize_tray.Checked == true)
                Hide();
        }

        private void Form1_Close(object sender, EventArgs e)
        {
            if (bIsUpdating == true)
            {
                // wait for the other thread to finish
                Thread.Sleep(100);
            }
            
        }

        private void checkBoxRemember_CheckedChanged(object sender, EventArgs e)
        {

            RegistryKey RegKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Hellau\\Properties");
            if (RegKey == null)
            {
                toolStripStatusLabel1.Text = "Failed to access Registry";
                toolStripStatusLabel1.ForeColor = Color.Red;
            }
            else
            {
                try
                {
                    if (checkBoxRemember.Checked == false)
                    {
                        RegKey.SetValue("domain", "");
                        RegKey.SetValue("password", "");
                        toolStripStatusLabel1.Text = "Removed from Registry";
                        toolStripStatusLabel1.ForeColor = Color.Green;
                    }
                    else
                    {
                        RegKey.SetValue("domain", textBoxURL.Text);
                        RegKey.SetValue("password", textBoxPassword.Text);
                        toolStripStatusLabel1.Text = "Saved to Registry";
                        toolStripStatusLabel1.ForeColor = Color.Green;
                    }

                }
                catch (Exception ex)
                {
                    toolStripStatusLabel1.Text = "Error: " + ex.Message;
                    notifyIcon1.ShowBalloonTip(500, "Hellau! Error", ex.Message, 0);
                    toolStripStatusLabel1.ForeColor = Color.Red;
                }
                finally
                {
                    RegKey.Close();
                }
            };
        }

        private void textBoxInfoText_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (checkBox_minimize_tray.Checked == true)
            {
                Hide();
                this.WindowState = FormWindowState.Minimized;
                if (mConnected == false)
                {
                    notifyIcon1.ShowBalloonTip(500, "Hellau!", "not connected!", 0);
                }
                else
                {
                    notifyIcon1.ShowBalloonTip(200, "Hellau!", "is connected!", 0);
                }
            }

        }

        protected override void WndProc(ref Message message)
        {
            base.WndProc(ref message);    // Process the message 

            if (mConnected == false || checkBox_MonitorClipboard.Checked == false)
            {
                return;
            }
            if (message.Msg == WM_DRAWCLIPBOARD)
            {
                String clipboardtext = (string) Clipboard.GetData(System.Windows.Forms.DataFormats.Text);
                if (clipboardtext == null)
                {
                    return;
                }
                if (clipboardtext.Contains("\n") == true)
                {
                    return;
                }

                Regex objNaturalPattern = new Regex("(?:https?://(?:(?:(?:(?:(?:[a-zA-Z\\d](?:(?:[a-zA-Z\\d]|-)*[a-zA-Z\\d])?)\\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\\d]|-)*[a-zA-Z\\d])?))|(?:(?:\\d+)(?:\\.(?:\\d+)){3}))(?::(?:\\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\\d$\\-_.+!*'(),]|(?:%[a-fA-F\\d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\\d$\\-_.+!*'(),]|(?:%[a-fA-F\\d]{2}))|[;:@&=])*))*)(?:\\?(?:(?:(?:[a-zA-Z\\d$\\-_.+!*'(),]|(?:%[a-fA-F\\d]{2}))|[;:@&=])*))?)?)");

                if (objNaturalPattern.IsMatch(clipboardtext) &&  clipboardtext.Contains("nzb") )
                    {
                        IHella hellaProxy = RPCConnect();
                        if (hellaProxy != null)
                            hellaProxy.EnqueueURL(clipboardtext);
                    }
                
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "nzb files (*.nzb)|*.nzb|All files (*.*)|*.*";
            openFileDialog1.Title = "Select a NZB file";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                String filename = openFileDialog1.FileName;
                MessageBox.Show("I wish I knew how to do this :(\nThis is not working yet!");
                // file code goes here
            }

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listBoxQueue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox queuelistbox = (ListBox)sender;
            iSelectedQueueItem = (String)queuelistbox.SelectedItem;
            textBoxQueueDetails.Text = "Updating...";

        }

        private void button_queueFORCE_Click(object sender, EventArgs e)
        {
            int iSelected = listBoxQueue.SelectedIndex;
            String szSelected = (String)listBoxQueue.SelectedItem;
            if (!mConnected == true)
                return;
            IHella hellaProxy = RPCConnect();
            if (hellaProxy == null)
                return;

            XmlRpcStruct StatusStruct;

            try
            {
                StatusStruct = hellaProxy.Status();
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                textBoxConnnectionStatus.BackColor = Color.Red;
                return;
            }

            // find the ID of the selected object
            object[] QueueArray = (object[])StatusStruct["queued"];
            foreach (object i in QueueArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;

                if (szSelected != null && szSelected.Equals((String)temp["nzbName"]))
                {
                    int QueueItemID = (Int32)temp["id"];
                    hellaProxy.Force(QueueItemID);
                }

            }


        }

        private IHella RPCConnect()
        {
            IHella hellaProxy;
            hellaProxy = XmlRpcProxyGen.Create<IHella>();
            try
            {
                hellaProxy.Url = textBoxURL.Text;
                hellaProxy.Credentials = new System.Net.NetworkCredential("hellanzb", textBoxPassword.Text);
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                return null;
            }
            return hellaProxy;
        }

         private void button_cancel_current_Click(object sender, EventArgs e)
        {
            int iSelected = listBoxQueue.SelectedIndex;
            String szSelected = (String)listBoxQueue.SelectedItem;
            if (!mConnected == true)
                return;
            IHella hellaProxy = RPCConnect();
            if (hellaProxy == null)
                return;

            XmlRpcStruct StatusStruct;

            try
            {
                StatusStruct = hellaProxy.Status();
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                textBoxConnnectionStatus.BackColor = Color.Red;
                return;
            }

            // find the ID of the current download

            object[] CurrentDownloadArray = (object[])StatusStruct["currently_downloading"];
            foreach (object i in CurrentDownloadArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;
                int QueueItemID = (Int32)temp["id"];
                hellaProxy.Cancel();
            }
            textBoxCDownloading.Text = "";
        }

        private void button_queue_CANCEL_Click(object sender, EventArgs e)
        {
            int iSelected = listBoxQueue.SelectedIndex;
            String szSelected = (String)listBoxQueue.SelectedItem;
            if (!mConnected == true)
                return;
            IHella hellaProxy = RPCConnect();
            if (hellaProxy == null)
                return;

            XmlRpcStruct StatusStruct;

            try
            {
                StatusStruct = hellaProxy.Status();
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                textBoxConnnectionStatus.BackColor = Color.Red;
                return;
            }

            // find the ID of the selected object
            object[] QueueArray = (object[])StatusStruct["queued"];
            foreach (object i in QueueArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;

                if (szSelected != null && szSelected.Equals((String)temp["nzbName"]))
                {

                    DialogResult result = MessageBox.Show(szSelected, "Cancel download", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        int QueueItemID = (Int32)temp["id"];
                        hellaProxy.Dequeue(QueueItemID);
                    }
                }

            }

        }

        private void button_queueUP_Click(object sender, EventArgs e)
        {
            int iSelected = listBoxQueue.SelectedIndex;
            String szSelected = (String)listBoxQueue.SelectedItem;
            if (!mConnected == true)
                return;
            IHella hellaProxy = RPCConnect();
            if (hellaProxy == null)
                return;

            XmlRpcStruct StatusStruct;

            try
            {
                StatusStruct = hellaProxy.Status();
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                textBoxConnnectionStatus.BackColor = Color.Red;
                return;
            }

            // find the ID of the selected object
            object[] QueueArray = (object[])StatusStruct["queued"];
            foreach (object i in QueueArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;

                if (szSelected != null && szSelected.Equals((String)temp["nzbName"]))
                {
                    int QueueItemID = (Int32)temp["id"];
                    hellaProxy.Up(QueueItemID, 1);
                }

            }
            textBoxQueueDetails.Text = "Updating...";

        }

        private void button_queueDOWN_Click(object sender, EventArgs e)
        {
            int iSelected = listBoxQueue.SelectedIndex;
            String szSelected = (String)listBoxQueue.SelectedItem;
            if (!mConnected == true)
                return;
            IHella hellaProxy = RPCConnect();
            if (hellaProxy == null)
                return;

            XmlRpcStruct StatusStruct;

            try
            {
                StatusStruct = hellaProxy.Status();
            }
            catch (Exception test)
            {
                textBoxConnnectionStatus.Text = test.Message;
                textBoxConnnectionStatus.BackColor = Color.Red;
                return;
            }

            // find the ID of the selected object
            object[] QueueArray = (object[])StatusStruct["queued"];
            foreach (object i in QueueArray)
            {
                XmlRpcStruct temp = (XmlRpcStruct)i;

                if (szSelected != null && szSelected.Equals((String)temp["nzbName"]))
                {
                    int QueueItemID = (Int32)temp["id"];

                    hellaProxy.Down(QueueItemID, 1);
                }

            }
            textBoxQueueDetails.Text = "Updating...";
        }

        private void textBoxStatus_TextChanged(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void button_edit_Click(object sender, EventArgs e)
        {
            checkBoxRemember.Checked = false;
            textBoxPassword.ReadOnly = false;
            textBoxURL.ReadOnly = false;

            // change the button text to "update"
            Update_Button.Text = "Connect";

            mConnected = false;
            textBoxConnnectionStatus.Text = "Disconnected!";
            textBoxConnnectionStatus.BackColor = Color.Yellow;
        }

        private void checkBoxAutoUpdate_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_Autostart_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_Autostart.Checked == true)
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                rkApp.SetValue("Hellau", Application.ExecutablePath.ToString());
            }
            else
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                rkApp.DeleteValue("Hellau", false);
            }
           
        }

        private void checkBox_StartMinimized_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_StartMinimized.Checked == true)
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
                rkApp.SetValue("Minimized", "TRUE");
            }
            else
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
                rkApp.SetValue("Minimized", "FALSE");
            }
        }

        private void checkBox_minimize_tray_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_minimize_tray.Checked == true)
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
                rkApp.SetValue("Tray", "TRUE");
            }
            else
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
                rkApp.SetValue("Tray", "FALSE");
            }
        }

        private void button_UploadURL_Click(object sender, EventArgs e)
        {
            IHella hellaProxy = RPCConnect();
            if (hellaProxy != null)
                hellaProxy.EnqueueURL(textBox_URL.Text);
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            // If the data is a file or a bitmap, display the copy cursor.
            if (e.Data.GetDataPresent(DataFormats.StringFormat) )
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }


        void Form_DragDrop(object sender, DragEventArgs e)
        {
            // Extract the data from the DataObject-Container into a string list
          String Url = (String) e.Data.GetData(DataFormats.StringFormat);

          IHella hellaProxy = RPCConnect();
          if (hellaProxy != null)
              hellaProxy.EnqueueURL(Url);
        
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bIsUpdating = false;
            Close();
        }

        private void checkBox_MonitorClipboard_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_MonitorClipboard.Checked == true)
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
                rkApp.SetValue("MonitorClipboard", "TRUE");
            }
            else
            {
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Hellau\\Properties", true);
                rkApp.SetValue("MonitorClipboard", "FALSE");
            }
        }

    }

  
    public interface IHella : IXmlRpcProxy
    {
        [XmlRpcMethod("status")]
        XmlRpcStruct Status();

        [XmlRpcMethod("pause")]
        XmlRpcStruct Pause();

        [XmlRpcMethod("continue")]
        XmlRpcStruct Continue();

        [XmlRpcMethod("force")]
        XmlRpcStruct Force(int nzbID);

        [XmlRpcMethod("dequeue")]
        void Dequeue(int nzbID);

        [XmlRpcMethod("down")]
        void Down(int nzbID, int amount);

        [XmlRpcMethod("up")]
        void Up(int nzbID, int amount);

        [XmlRpcMethod("cancel")]
        void Cancel();

        [XmlRpcMethod("enqueueurl")]
        void EnqueueURL(String URL);

    }
}